<?php

namespace liketp\database\connection;

use liketp\database\Connection;
use PDO;

class Mysql extends Connection
{

    protected static $defaultConfig = [
        'hostname' => '127.0.0.1',
        'hostport' => 3306,
        'username' => '',
        'password' => '',
        'database' => '',
        'charset'  => 'utf8',
        'prefix'   => ''
    ];

    public static function flag(array $config): string
    {
        $flagData = [
            'type' => $config['type'] ?? '',
            'host' => $config['host'] ?? '',
            'port' => $config['port'] ?? '',
            'dbname' => $config['database'] ?? '',
            'account' => $config['user'] ?? ''
        ];
        return md5(json_encode($flagData));
    }

    protected function createPdo()
    {
        $username = $this->config['username'];
        $password = $this->config['password'];
        return new PDO($this->dsn(), $username, $password);
    }

    protected function initialize()
    {
        $this->pdo->exec('set names ' . $this->config['charset']);
    }

    protected function dsn()
    {
        $hostname = $this->config['hostname'];
        $hostport = $this->config['hostport'];
        $database = $this->config['database'];
        return "mysql:host=$hostname;port=$hostport;dbname=$database";
    }
}
